package bajo.src;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

import javax.microedition.io.Connector;
import javax.microedition.io.HttpConnection;

import net.rim.blackberry.api.browser.URLEncodedPostData;
import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Font;
import net.rim.device.api.ui.Manager;
import net.rim.device.api.ui.UiApplication;
import net.rim.device.api.ui.component.ButtonField;
import net.rim.device.api.ui.component.Dialog;
import net.rim.device.api.ui.component.LabelField;
import net.rim.device.api.ui.container.HorizontalFieldManager;
import net.rim.device.api.ui.container.MainScreen;
import net.rim.device.api.ui.container.VerticalFieldManager;


public class RegisterPage extends MainScreen {
	
	private LoginScreen logInScreen;
	
	private RegisterPage me;
	
	private HorizontalFieldManager horManager;
	private HorizontalFieldManager horButtonManager;
	private VerticalFieldManager verLabelManager;
	private VerticalFieldManager verTxtManager;
	
	private LabelField title;
	
	private TextBoxField firstNameTxt;
	private TextBoxField lastNameTxt;
	private TextBoxField userNameTxt;
	private TextBoxField passwordTxt;
	private TextBoxField retypePasswordTxt;
	private TextBoxField emailTxt;
	
	private ButtonField submit;
	private ButtonField cancel;
	
	private String firstNameStr;
	private String lastNameStr;
	private String userNameStr;
	private String passwordStr;
	private String emailStr;
	
	private final String TITLE = "BAJO Registration!";
	
	public RegisterPage(LoginScreen ls) {
		logInScreen = ls;
		me = this;
		
		horManager = new HorizontalFieldManager();
		
		horButtonManager = new HorizontalFieldManager();
		verLabelManager = new VerticalFieldManager();
		verTxtManager = new VerticalFieldManager();
		
		title = new LabelField(TITLE, Manager.FIELD_HCENTER);
		title.setFont(Font.getDefault().derive(Font.BOLD, 30));
		
		verLabelManager.add(new LabelField("First Name: "));
		verLabelManager.add(new LabelField("Last Name: "));
		verLabelManager.add(new LabelField("Username: "));
		verLabelManager.add(new LabelField("Password: "));
		verLabelManager.add(new LabelField("Retype Password: "));
		verLabelManager.add(new LabelField("Email: "));
		
		firstNameTxt = new TextBoxField(25, 275, false);
		lastNameTxt = new TextBoxField(25, 275, false);
		userNameTxt = new TextBoxField(25, 275, false);
		passwordTxt = new TextBoxField(25, 275, true);
		retypePasswordTxt = new TextBoxField(25, 275, true);
		emailTxt = new TextBoxField(25, 275, false);
		
		verTxtManager.add(firstNameTxt);
		verTxtManager.add(lastNameTxt);
		verTxtManager.add(userNameTxt);
		verTxtManager.add(passwordTxt);
		verTxtManager.add(retypePasswordTxt);
		verTxtManager.add(emailTxt);
		
		horManager.add(verLabelManager);
		horManager.add(verTxtManager);
		
		submit = new ButtonField("Submit");
		submit.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				passwordStr = passwordTxt.getText();
				
				// If we have empty fields.
				if (firstNameTxt.getText().equals("") || lastNameTxt.getText().equals("")
					|| lastNameTxt.getText().equals("") || userNameTxt.getText().equals("")
						|| emailTxt.getText().equals("") || passwordStr.equals("")
							|| retypePasswordTxt.getText().equals("")) {
					Dialog.alert("One or more of the Fields is Empty!");
				// If password and retype password is not the same.
				} else if (passwordStr.equals(retypePasswordTxt.getText())) {
					firstNameStr = firstNameTxt.getText();
					lastNameStr = lastNameTxt.getText();
					userNameStr = userNameTxt.getText();
					emailStr = emailTxt.getText();
					
					//TODO: Send to Database.
					String url = Constants.BASE_TOMCAT_ADDR + Constants.REGISTER_PAGE;
					URLEncodedPostData postData = new URLEncodedPostData(URLEncodedPostData.DEFAULT_CHARSET, false);
					postData.append("userId", userNameStr);
					postData.append("firstName",firstNameStr);
					postData.append("lastName",lastNameStr);
					postData.append("password", passwordStr);
					
					HTTPDataThread sendThread = new HTTPDataThread(url, postData, HttpConnection.POST);
					sendThread.start();
					try {
						sendThread.join();
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
										
					//To do: check for connection
					String[] retData = null;
					synchronized (HTTPDataThread.global_lock) {
						retData = HTTPDataThread.copyData();
					}
				
					if( retData[0].equals("0")){
						Dialog.alert("Already Existing Username!");
						userNameTxt.setText("");
						userNameTxt.setFocus();
					}else{
					
						// Go back to Login ge with the user name and password.
						logInScreen.getUserNameField().setText(userNameStr);
						logInScreen.getPasswordField().setText(passwordStr);
						UiApplication.getUiApplication().popScreen(me);
					}
				} else {
					Dialog.alert("Password is Not Same as Retyped Password!");
				}
			}
		});
		
		cancel = new ButtonField("Cancel");
		cancel.setChangeListener(new FieldChangeListener() {
			public void fieldChanged(Field field, int context) {
				UiApplication.getUiApplication().popScreen(me);
			}
		});
		
		horButtonManager.add(submit);
		horButtonManager.add(cancel);
		
		add(title);
		add(horManager);
		add(horButtonManager);
	}
	
	/*
	 * Overridden function to get rid of the menu when switching to a 
	 * new main screen.
	 */
	public boolean onMenu(int instance) {
		return true;
	}

	/*
	 * Overridden function used to get rid of the save prompt
	 * when exiting the MainScreen.
	 */
	protected boolean onSavePrompt(){
		return true;
	}
	

}
